#include "library.h"
LIST_HEAD(book_list);
LIST_HEAD(borrow_record);
void show_all_books()
{
    printf("\n图书列表:\n");
    printf("%-10s %-30s %-20s %-25s  %-10s %-6s\n",
           "图书ID",
           "书名",
           "作者",
           "出版社",
           "价格",
           "库存");
    printf("========================================================================================================\n");

    Book *book;
    list_for_each_entry(book, &book_list, list)
    {
        printf("%-10s %-30s %-20s %-25s %-10.2f %-6d\n",
               book->id, book->name, book->author,
               book->publisher, book->price, book->stock);
    }
}

void book_management()
{
    int choice;
    do
    {
        printf("\n=== 图书管理 ===\n");
        printf("1. 添加图书\n");
        printf("2. 删除图书\n");
        printf("3. 修改图书信息\n");
        printf("4. 搜索图书\n");
        printf("5. 返回上级菜单\n");
        printf("请选择操作 (1-5): ");

        if (scanf("%d", &choice) != 1)
        {
            clear_input_buffer();
            printf("无效输入，请输入数字\n");
            continue;
        }
        clear_input_buffer();

        switch (choice)
        {
        case 1:
            add_book();
            break;
        case 2:
            delete_book();
            break;
        case 3:
            modify_book();
            break;
        case 4:
            search_book();
            break;
        case 5:
            return;
        default:
            printf("无效操作\n");
        }
    } while (1);
}

// 添加图书
void add_book()
{
    Book *new_book = malloc(sizeof(Book));
    if (!new_book)
    {
        perror("内存分配错误");
        return;
    }

    memset(new_book, 0, sizeof(Book));

    printf("\n=== 添加图书 ===\n");

    while (1)
    {
        printf("\n图书ID: ");
        fgets(new_book->id, sizeof(new_book->id), stdin);
        new_book->id[strcspn(new_book->id, "\n")] = '\0';

        if (strlen(new_book->id) == 0)
        {
            printf("图书ID不能为空！\n");
            continue;
        }

        // 检查ID是否唯一
        Book *b;
        int id_exists = 0;
        list_for_each_entry(b, &book_list, list)
        {
            if (strcmp(b->id, new_book->id) == 0)
            {
                id_exists = 1;
                break;
            }
        }

        if (id_exists)
        {
            printf("该图书ID已存在，请重新输入\n");
        }
        else
        {
            break; // ID有效，退出循环
        }
    }

    printf("\n书名:");
    fgets(new_book->name, sizeof(new_book->name), stdin);
    new_book->name[strcspn(new_book->name, "\n")] = '\0';

    printf("\n作者:");
    fgets(new_book->author, sizeof(new_book->author), stdin);
    new_book->author[strcspn(new_book->author, "\n")] = '\0';

    printf("\n出版社:");
    fgets(new_book->publisher, sizeof(new_book->publisher), stdin);
    new_book->publisher[strcspn(new_book->publisher, "\n")] = '\0';

    printf("\n价格：");
    scanf("%f", &new_book->price);
    while (getchar() != '\n')
        ;

    printf("\n库存：");
    scanf("%d", &new_book->stock);
    while (getchar() != '\n')
        ;

    INIT_LIST_HEAD(&new_book->list);
    list_add_tail(&new_book->list, &book_list);
}

// 删除书籍
void delete_book()
{
    char book_id[20];
    printf("\n=== 删除书籍 ===\n");
    printf("输入要删除的图书的ID:");
    fgets(book_id, sizeof(book_id), stdin);
    book_id[strcspn(book_id, "\n")] = '\0';

    Book *book, *tmp;
    int found = 0;
    list_for_each_entry_safe(book, tmp, &book_list, list)
    {
        if (strcmp(book->id, book_id) == 0)
        {
            found = 1;
            list_del(&book_list);
            free(book);
            printf("删除成功");
            break;
        }
    }
    if (!found)
    {
        printf("找不到该书籍");
    }
}

// 借阅书籍
void borrow_book()
{
    char book_id[20];
    printf("\n=== 借阅书籍 ===\n");
    printf("输入要借阅的书籍的ID:");
    fgets(book_id, sizeof(book_id), stdin);
    book_id[strcspn(book_id, "\n")] = '\0';

    Book *book;
    int found = 0;
    list_for_each_entry(book, &book_list, list)
    {
        if (strcmp(book->id, book_id) == 0)
        {
            found = 1;
            if (book->stock > 0)
                book->stock--;
            printf("借阅成功");

            BorrowRecord *record = malloc(sizeof(BorrowRecord));
            strncpy(record->book_id, book->id, sizeof(record->book_id));
            record->borrow_time = time(NULL);
            INIT_LIST_HEAD(&record->list);
            list_add_tail(&record->list, &current_user->borrowed_books);
        }
        else
        {
            printf("库存不足");
        }
    }
    if (!found)
    {
        printf("找不到该图书");
    }
}

// 归还图书
void return_book()
{
    char book_id[20];
    printf("\n=== 归还 ===\n");
    printf("请输入要归还的图书ID:");
    fgets(book_id, sizeof(book_id), stdin);
    book_id[strcspn(book_id, "\n")] = '\0';

    Book *book;
    int found_book = 0;
    if (strcmp(book->id, book_id) == 0)
    {
        list_for_each_entry(book, &book_list, list)
        {
            found_book = 1;
            break;
        }
    }
    if (!found_book)
    {
        printf("未找到该书籍");
        return;
    }

    Book *borrowed, *tmp;
    int found = 0;
    list_for_each_entry_safe(borrowed, tmp, &current_user->borrowed_books, list)
    {
        if (strcmp(borrowed->id, book->id) == 0)
        {
            found = 1;
            Book *original;
            list_for_each_entry(original, &book_list, list)
            {
                if (strcmp(original->id, book_id) == 0)
                {
                    original->stock++;
                    break;
                }
            }

            list_del(&borrowed->list);
            free(borrowed);
            break;
        }
    }
    if (!found)
    {
        printf("您未借阅此书\n");
    }
}

// 借阅记录
void show_borrowed_books()
{
    printf("\n=== 借阅记录 ===\n");
    // if (list_empty(&current_user->borrowed_books))
    // {
    //     printf("未借阅如何书籍\n");
    // }
    // else
    // {
    //     printf("%-10s %-20s %-15s", "ID",
    //                                 "书名",
    //                                 "作者");

    //     Book *book;
    //     list_for_each_entry(book, &current_user->borrowed_books, list)
    //     {
    //         printf("%-10s %-20s %-15s", book->id,
    //                book->name,
    //                book->author);
    //     }
    // }
    if (list_empty(&current_user->borrowed_books))
    {
        printf("\n您没有借阅任何图书\n");
        return;
    }

    printf("\n%-10s %-30s %-20s\n", "图书ID", "书名", "借阅时间");
    printf("------------------------------------------------\n");

    BorrowRecord *record;
    list_for_each_entry(record, &current_user->borrowed_books, list)
    {
        // 查找图书信息
        Book *book;
        char book_name[50] = "未知";
        char author[30] = "未知";

        list_for_each_entry(book, &book_list, list)
        {
            if (strcmp(book->id, record->book_id) == 0)
            {
                strncpy(book_name, book->name, sizeof(book_name));
                strncpy(author, book->author, sizeof(author));
                break;
            }
        }

        // 格式化时间
        char time_str[20];
        struct tm *timeinfo = localtime(&record->borrow_time);
        strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", timeinfo);

        printf("%-10s %-30s %-20s\n", record->book_id, book_name, time_str);
    }
}

// 查找图书
void search_book()
{
    char keyword[50];
    printf("\n=== 查找图书 ===\n");
    printf("输入要查找的书籍名字或作者");
    fgets(keyword, sizeof(keyword), stdin);
    keyword[strcspn(keyword, "\n")] = '\0';

    printf("\n搜索结果:\n");
    printf("%-10s %-20s %-15s %-20s %-8s %-6s\n",
           "ID", "书名", "作者", "出版社", "价格", "库存");

    int found = 0;
    Book *book;
    list_for_each_entry(book, &book_list, list)
    {
        if (strstr(book->name, keyword) ||
            strstr(book->author, keyword))
        {
            found = 1;
            printf("%-10s %-20s %-15s %-20s %-8.2f %-6d\n",
                   book->id, book->name, book->author,
                   book->publisher, book->price, book->stock);
        }
    }
    if (!found)
    {
        printf("找不到匹配的书籍");
    }
}

// 修改图书
void modify_book()
{
    char book_id[20];
    printf("\n--- 修改图书信息 ---\n");
    printf("请输入要修改的图书ID: ");
    fgets(book_id, sizeof(book_id), stdin);
    book_id[strcspn(book_id, "\n")] = '\0';

    Book *book;
    int found = 0;
    list_for_each_entry(book, &book_list, list)
    {
        if (strcmp(book->id, book_id) == 0)
        {
            found = 1;
            printf("当前信息:\n");
            printf("ID: %s\n", book->id);
            printf("书名: %s\n", book->name);
            printf("作者: %s\n", book->author);
            printf("出版社: %s\n", book->publisher);
            printf("价格: %.2f\n", book->price);
            printf("库存: %d\n", book->stock);

            printf("请输入要修改的信息");
            char input[100];

            printf("新书名");
            fgets(input, sizeof(input), stdin);
            // while(getchar()!='\n');
            if (input[0] != '\n')
            {
                input[strcspn(input, "\n")] = '\0';
                strncpy(book->name, input, sizeof(book->name));
            }

            printf("新作者:");
            fgets(input, sizeof(input), stdin);
            while (getchar() != '\n')
                ;
            if (input[0] != '\n')
            {
                input[strcspn(input, "\n")] = '\0';
                strncpy(book->author, input, sizeof(book->author));
            }
            printf("新出版社:");
            fgets(input, sizeof(input), stdin);
            while (getchar() != '\n')
                ;
            if (input[0] != '\n')
            {
                input[strcspn(input, "\n")] = '\0';
                strncpy(book->publisher, input, sizeof(book->publisher));
            }

            printf("新价格:");
            fgets(input, sizeof(input), stdin);
            while (getchar() != '\n')
                ;
            if (input[0] != '\n')
            {
                book->price = atof(input);
            }

            printf("新库存:");
            fgets(input, sizeof(input), stdin);
            while (getchar() != '\n')
                ;
            if (input[0] != '\n')
            {
                book->stock = atof(input);
            }

            printf("修改成功");
            break;
        }
    }
    if (!found)
    {
        printf("找不到该书籍\n");
    }
}

// void show_books_status()
// {

// }